﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using DAL;

namespace CTRL
{
    public sealed class CtrlCustomer
    {
        private static volatile CtrlCustomer instance;
        private static object syncRoot = new Object();

        private IDALCustomer customerRepo;

        public CtrlCustomer()
        {
            this.customerRepo = new DALCustomer(new CarBatteryEntities());
        }

        public static CtrlCustomer Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new CtrlCustomer();
                    }
                }

                return instance;
            }
        }

        public int CreateCustomer(string _name, string _username, string _password, string _email)
        {
            customerRepo.InsertCustomer(new Customer() { name = _name, username = _username, password = _password, email = _email });

            return customerRepo.Save();
        }

        public int UpdateCustomer(int ID, string _name, string _username, string _password, string _email)
        {
            Customer customer = GetCustomer(ID);

            if (customer != null)
            {
                customer.name = _name;
                customer.password = _password;
                customer.username = _username;
                customer.email = _email;

                customerRepo.UpdateCustomer(customer);
            }

            return customerRepo.Save();
        }

        public int DeleteCustomer(int ID)
        {
            Customer customer = GetCustomer(ID);
            CtrlCar carCtrl = CtrlCar.Instance;

            if (customer != null)
            {
                customerRepo.DeleteCustomer(ID);
                carCtrl.DeleteCarsOwnedByCustomer(ID);
            }
            return customerRepo.Save();
        }

        public IEnumerable<Customer> GetAllCustomers()
        {
            return customerRepo.GetCustomers();
        }

        public Customer GetCustomer(int customerID)
        {
            return customerRepo.GetCustomerByID(customerID);
        }

        public Customer GetCustomerByName(string customerName)
        {
            return customerRepo.GetCustomerByName(customerName);
        }

        public Customer CheckLoginCredentials(string username, string password)
        {
            return customerRepo.CheckLoginCredentials(username, password);
        }
    }
}